import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:go_router/go_router.dart';
import 'package:leader_doctor_flutter/common/data/app.dart';
import 'package:leader_doctor_flutter/common/data/entity.dart';
import 'package:leader_doctor_flutter/common/utils/log_utils.dart';
import 'package:leader_doctor_flutter/common/widget/comm_widget.dart';
import 'package:leader_doctor_flutter/common/widget/long_press_container.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../../../common/http/api.dart';
import '../../../common/http/http_client.dart';
import '../../../common/http/url_helper.dart';
import '../../../model/app_version.dart';
import '../../../plugins/plugins_messages.g.dart';
import '../../../router/router.dart';

class AboutPage extends StatefulWidget {
  const AboutPage({super.key});

  @override
  State<AboutPage> createState() => _AboutPageState();
}

class _AboutPageState extends State<AboutPage> {
  var _hasNewsVersion = false;
  final Future<SharedPreferences> _prefs = SharedPreferences.getInstance();

  @override
  void initState() {
    super.initState();
    _checkAppNewVersion();
  }

  @override
  Widget build(BuildContext context) {
    var packageInfo = App.instance.packageInfo;
    var serviceInfo = App.instance.serviceInfo;
    return Scaffold(
      appBar: CommWidget.getCommAppbar(context),
      body: Container(
        color: Colors.white,
        width: double.infinity,
        height: double.infinity,
        padding: EdgeInsets.only(left: 12.w, right: 12.w),
        // decoration: const BoxDecoration(color: Colors.orange),
        child: SingleChildScrollView(
            child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            LongPressContainer(
                childView: Container(
                    alignment: Alignment.center,
                    margin: EdgeInsets.only(top: 32.w),
                    child: Image.asset("assets/logo/logo.png", width: 74.w, height: 74.w)),
                duration: 10,
                function: _longPressFunc),
            SizedBox(height: 18.w),
            Text(
              "领医未来",
              style: TextStyle(fontSize: 16.sp, color: const Color(0xFF333333)),
            ),
            SizedBox(height: 10.w),
            Text(
              "Version ${packageInfo?.appVersionName}",
              style: TextStyle(fontSize: 16.sp, color: const Color(0xFF878787)),
            ),
            SizedBox(height: 52.w),
            CommWidget.buildLine(),
            buildNewVersionItem("检查更新", () async {
              await NativeInterface().checkAppUpdate();
            }),
            CommWidget.buildLine(),
            buildItemView("分享下载", (s) async {
              await NativeInterface().shareDownloadQr();
            }),
            CommWidget.buildLine(),
            buildItemView("帮助中心", (s) {
              _launchInBrowserView(s, UrlHelper.loadUrl(Api.helperCenter));
            }),
            CommWidget.buildLine(),
            buildItemView("服务报价", (s) {
              _launchInBrowserView(s, UrlHelper.loadUrl(Api.serviceOffer));
            }),
            CommWidget.buildLine(),
            buildItemView("协议中心", (s) {
              context.push(PageUrl.myProtocolList);
            }),
            SizedBox(height: 80.w),
            Text(
              "版权所有",
              style: TextStyle(fontSize: 13.sp, color: const Color(0xFF333333)),
            ),
            SizedBox(height: 5.w),
            Text(
              "陕西医智诺信息科技有限公司",
              style: TextStyle(fontSize: 12.sp, color: const Color(0xFF999999)),
            ),
          ],
        )),
      ),
    );
  }

  GestureDetector buildItemView(String titleStr, Function(String title) onTop) {
    return GestureDetector(
        behavior: HitTestBehavior.opaque,
        onTap: () => onTop.call(titleStr),
        child: Container(
            height: 52.w,
            alignment: Alignment.centerLeft,
            child: Row(children: [
              Expanded(
                  child: Text(
                titleStr,
                style: TextStyle(fontSize: 16.sp, color: const Color(0xFF333333)),
              )),
              Image.asset("assets/images/grey_setup.webp", width: 6.w, height: 12.w),
            ])));
  }

  ///检查更新
  GestureDetector buildNewVersionItem(String titleStr, Function onTop) {
    return GestureDetector(
        behavior: HitTestBehavior.opaque,
        onTap: () => onTop.call(),
        child: Container(
            height: 52.w,
            alignment: Alignment.centerLeft,
            child: Row(children: [
              Expanded(
                  child: Row(
                children: [
                  Text(
                    titleStr,
                    style: TextStyle(fontSize: 16.sp, color: const Color(0xFF333333)),
                  ),
                  Visibility(
                      visible: _hasNewsVersion,
                      child: Container(
                          margin: EdgeInsets.only(left: 5.w),
                          width: 48.w,
                          height: 24.w,
                          alignment: Alignment.center,
                          decoration: BoxDecoration(
                              color: const Color(0xFFFF6565), borderRadius: BorderRadius.all(Radius.circular(12.w))),
                          child: Text(
                            "NEW",
                            style: TextStyle(fontSize: 13.sp, color: const Color(0xFFFFFFFF)),
                          )))
                ],
              )),
              Image.asset("assets/images/grey_setup.webp", width: 6.w, height: 12.w),
            ])));
  }

  ///联系电话
  GestureDetector buildServiceItem(String titleStr, String phoneNumber, Function onTop) {
    return GestureDetector(
        behavior: HitTestBehavior.opaque,
        onTap: () => onTop.call(),
        child: Container(
            height: 52.w,
            alignment: Alignment.centerLeft,
            child: Row(children: [
              Expanded(
                  child: Text(
                titleStr,
                style: TextStyle(fontSize: 16.sp, color: const Color(0xFF333333)),
              )),
              Text(phoneNumber, style: TextStyle(fontSize: 15.sp, color: const Color(0xFF999999))),
            ])));
  }

  void _longPressFunc() async {
    var sharedPreferences = await _prefs;
    sharedPreferences.setBool(Entity.jumpFace, true);
  }

  /// 检查更新
  void _checkAppNewVersion() async {
    var httpRequest = HttpRequest(Api.checkUpdate, urlParams: {'appType': 'android'}, isShowLoading: false);
    var httpResponse = await HttpClient.get(httpRequest);
    var serviceResult = ServiceResult<AppVersion?>(httpResponse, (map) => AppVersion.fromJson(map));
    var appVersion = serviceResult.responseBody;
    var packageInfo = App.instance.packageInfo;
    var currentVersionCode = int.parse(packageInfo?.appVersionCode ?? "-1");
    var serverVersionCode = int.parse(appVersion?.versionCode ?? "-1");
    if (currentVersionCode != -1 && serverVersionCode != -1 && serverVersionCode > currentVersionCode) {
      _hasNewsVersion = true;
      setState(() {});
    }
  }

  _launchInBrowserView(String title, String url) async {
    await UrlHelper.loadH5Page(title, url);
  }
}
